package club.chenlinghong.order.controller;

import club.chenlinghong.order.client.ProductClient;
import club.chenlinghong.order.dto.CartDTO;
import club.chenlinghong.order.entity.ProductInfo;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.cloud.client.ServiceInstance;
import org.springframework.cloud.client.loadbalancer.LoadBalancerClient;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.client.RestTemplate;

import java.util.Arrays;
import java.util.List;

/**
 * @Description TODO
 * @Author chenlinghong
 * @Date 2019/7/1 13:42
 * @Version V1.0
 */
@RestController
@Slf4j
@RequestMapping("/order")
public class ClientController {

    // @Autowired
    // private LoadBalancerClient loadBalancerClient;

    // @Autowired
    // private RestTemplate restTemplate;

    @Autowired
    private ProductClient productClient;

    @GetMapping("/product")
    public String getProductMsg() {
        // 1.第一种方式
        /**
         * 第一种方式：直接使用restTemplate，url写死
         */
        // RestTemplate restTemplate = new RestTemplate();
        // String response = restTemplate.getForObject("http://localhost:8080/msg", String.class);
        // log.info("response={}",response);

        /**
         * 第二种方式，解决多个IP问题
         * 利用loadBalancerClient通过应用名获取host,port，然后再使用restTemplate
         */
        // RestTemplate restTemplate = new RestTemplate();
        // ServiceInstance serviceInstance = loadBalancerClient.choose("PRODUCT");
        // String url = String.format("http://%s:%s", serviceInstance.getHost(), serviceInstance.getPort() + "/msg");
        // String response = restTemplate.getForObject(url, String.class);
        // log.info("response={}", response);

        /**
         * 第三种方式：采用注解
         */
        // String response = restTemplate.getForObject("http://PRODUCT/msg", String.class);

        /**
         * 使用feign
         */
        String response = productClient.productMsg();
        return response;
    }

    /**
     * 获取商品列表
     *
     * @return
     */
    @GetMapping("/getProductList")
    public String getProductList() {
        List<ProductInfo> productInfoList = productClient.listForProduct(Arrays.asList("123456789"));
        log.info("productInfoList={}", productInfoList);
        return "ok";
    }

    /**
     * 扣库存
     *
     * @return
     */
    @GetMapping("/productDecreaseStock")
    public String productDecreaseStock() {
        productClient.decreaseStock(Arrays.asList(new CartDTO("123456789", 1)));
        return "ok";
    }


}
